package org.kiwi.job.util;

import org.springframework.aop.framework.Advised;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/2/19.
 */
public class MethodInvoker {

    private final Object object;

    private final Method method;

    private final Class<?>[] parameterTypes;

    private volatile Object target;

    public MethodInvoker(Object object, Method method) {
        Assert.notNull(object, "Object to invoke must not be null");
        Assert.notNull(method, "Method to invoke must not be null");
        this.method = method;
        method.setAccessible(true);
        this.object = object;
        this.parameterTypes = method.getParameterTypes();
    }

    public MethodInvoker(Object object, String methodName, Class<?>... paramTypes) {
        Assert.notNull(object, "Object to invoke must not be null");
        Method method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, paramTypes);
        if (method == null) {
            // try with no params
            method = ClassUtils.getMethodIfAvailable(object.getClass(), methodName, new Class[]{});
        }

        Assert.notNull(method, "No methods found for name: [" + methodName + "] in class: ["
                + object.getClass() + "] with arguments of type: [" + Arrays.toString(paramTypes) + "]");

        this.object = object;
        this.method = method;
        method.setAccessible(true);
        this.parameterTypes = method.getParameterTypes();
    }


    public Object invokeMethod(Object... args) {
        Assert.state(this.parameterTypes.length == args.length,
                "Wrong number of arguments, expected no more than: [" + this.parameterTypes.length + "]");

        try {
            // Extract the target from an Advised as late as possible
            // in case it contains a lazy initialization
            Object target = extractTarget(this.object, this.method);
            return method.invoke(target, args);
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to invoke method: [" + this.method + "] on object: ["
                    + this.object + "] with arguments: [" + Arrays.toString(args) + "]", e);
        }
    }

    private Object extractTarget(Object target, Method method) {
        if (this.target == null) {
            if (target instanceof Advised) {
                Object source;
                try {
                    source = ((Advised) target).getTargetSource().getTarget();
                } catch (Exception e) {
                    throw new IllegalStateException("Could not extract target from proxy", e);
                }
                if (source instanceof Advised) {
                    source = extractTarget(source, method);
                }
                if (method.getDeclaringClass().isAssignableFrom(source.getClass())) {
                    target = source;
                }
            }
            this.target = target;

        }
        return this.target;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof MethodInvoker)) {
            return false;
        }

        if (obj == this) {
            return true;
        }
        MethodInvoker rhs = (MethodInvoker) obj;
        return (rhs.method.equals(this.method)) && (rhs.object.equals(this.object));
    }

    @Override
    public int hashCode() {
        int result = 25;
        result = 31 * result + this.object.hashCode();
        result = 31 * result + this.method.hashCode();
        return result;
    }
}
